package org.gbif.agi.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.appfuse.service.GenericManager;
import org.gbif.agi.model.GenusRelationship;
import org.appfuse.webapp.action.BaseAction;

import java.util.List;

public class GenusRelationshipAction extends BaseAction implements Preparable {
    private GenericManager<GenusRelationship, Long> genusRelationshipManager;
    private List genusRelationships;
    private GenusRelationship genusRelationship;
    private Long  id;

    public void setGenusRelationshipManager(GenericManager<GenusRelationship, Long> genusRelationshipManager) {
        this.genusRelationshipManager = genusRelationshipManager;
    }

    public List getGenusRelationships() {
        return genusRelationships;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String genusRelationshipId = getRequest().getParameter("genusRelationship.id");
            if (genusRelationshipId != null && !genusRelationshipId.equals("")) {
                genusRelationship = genusRelationshipManager.get(new Long(genusRelationshipId));
            }
        }
    }

    public String list() {
        genusRelationships = genusRelationshipManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public GenusRelationship getGenusRelationship() {
        return genusRelationship;
    }

    public void setGenusRelationship(GenusRelationship genusRelationship) {
        this.genusRelationship = genusRelationship;
    }

    public String delete() {
        genusRelationshipManager.remove(genusRelationship.getId());
        saveMessage(getText("genusRelationship.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            genusRelationship = genusRelationshipManager.get(id);
        } else {
            genusRelationship = new GenusRelationship();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (genusRelationship.getId() == null);

        genusRelationshipManager.save(genusRelationship);

        String key = (isNew) ? "genusRelationship.added" : "genusRelationship.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}